//
//  CZComposePictureView.swift
//  Blog
//
//  Created by whitcast on 16/7/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let CZComposePictureViewCellIdentifier = "CZComposePictureViewCellIdentifier"

class CZComposePictureView: UICollectionView {
    // 存储添加图片
    lazy var images = [UIImage]()
    // 点击加号按钮执行闭包
    var didSelectedAddClosure: (() -> ())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI() {
        registerClass(CZComposePictureViewCell.self, forCellWithReuseIdentifier: CZComposePictureViewCellIdentifier)
        // 设置代理
        delegate = self
        // 设置数据源代理
        dataSource = self
        // 默认隐藏配图
        hidden = true
    }
    func addImage(image: UIImage) {
        // 显示配图
        hidden = false
        // 添加图片
        images.append(image)
        // 重新加载数据
        reloadData()
    }
    
    override func layoutSubviews() {
         super.layoutSubviews()
        // 每项之间的间距
        let itemMargin: CGFloat = 5
        // 每项大小
        let itewWidth = (width - 2 * itemMargin) / 3
        
        // 获取布局方式
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置大小
        flowLayout.itemSize = CGSize(width: itewWidth, height: itewWidth)
        // 设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        // 设置垂直间距
        flowLayout.minimumInteritemSpacing = itemMargin
    }
    
   
}

extension CZComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate{

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 9 || images.count == 0 {
            return images.count
        } else {
            return images.count + 1
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZComposePictureViewCellIdentifier, forIndexPath: indexPath) as! CZComposePictureViewCell
        if indexPath.item == images.count {
            // 设置加号按钮
            cell.image = nil
        } else {
            cell.image  = images[indexPath.item]
        }
        // 设置闭包
        cell.deleteButtonClosure = {
            self.images.removeAtIndex(indexPath.item)
            
            if self.images.count == 0 {
                self.hidden = true
            }
            // 重新加载数据
            self.reloadData()
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 表示加号按钮
        if indexPath.item == images.count {
            // 取消选择，支持高亮图片
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            // 执行闭包
            didSelectedAddClosure?()
        }
    }
    
}

// 配图cell
class CZComposePictureViewCell: UICollectionViewCell {
    // 点击删除按钮的闭包
    var deleteButtonClosure: (()->())?

    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                // 隐藏删除按钮
                deleteButton.hidden = true

            } else {
                imageView.image = image
                deleteButton.hidden = false
            }
        }
    }
    // MARK:    --懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //  删除按钮
    private lazy var deleteButton: UIButton = {
        
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
        
    }
    @objc private func deleteButtonAction() {
        deleteButtonClosure?()
    }


}
